import { observe } from "./observe/index";

export function initState(vm) {
  const opts = vm.$options; // 获取所有的选项
  if (opts.data) {
    initData(vm);
  }
}

function proxy(vm, target, key) {
  Object.defineProperty(vm, key, {
    enumerable: true,
    configurable: true,
    get() {
      return vm[target][key];
    },
    set(val) {
      vm[target][key] = val;
    },
  });
}

/** 初始化 data */
function initData(vm) {
  // 对数据进行劫持
  let data = vm.$options.data;
  data = typeof data === "function" ? data.call(vm) : data;
  observe(data);
  vm._data = data;
  for (const key in data) {
    proxy(vm, "_data", key);
  }
}
